package org.apache.servicecomb.samples.practise.houserush.customer.manage.api;

import org.apache.servicecomb.provider.rest.common.RestSchema;
import org.apache.servicecomb.samples.practise.houserush.customer.manage.aggregate.Customer;
import org.apache.servicecomb.samples.practise.houserush.customer.manage.aggregate.Qualification;
import org.apache.servicecomb.samples.practise.houserush.customer.manage.service.CustomerManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: Snake Man
 * @system:
 * @DateTime: 2022/1/19 22:07
 * @Description:
 */
@RestSchema(schemaId = "customerManageApiRest")
@RequestMapping("/")
public class CustomerManageApiRestImpl implements CustomerManageApi {

    @Autowired
    private CustomerManageService customerManageService;


    /**
     * 根据id查询客户
     *
     * @param id
     * @return
     */
    @GetMapping("customers/{id}")
    public Customer findCustomer(@PathVariable("id") int id) {
        return customerManageService.findCustomer(id);
    }

    /**
     * 查询所有客户
     *
     * @return
     */
    @GetMapping("customers")
    public List<Customer> indexCustomers() {
        return customerManageService.indexCustomers();
    }

    /**
     * 创建客户
     *
     * @param customer
     * @return
     */
    @PostMapping("customers")
    public Customer createCustomer(@RequestBody Customer customer) {
        return customerManageService.createCustomer(customer);
    }



    /**
     * 根据id修改客户信息
     *
     * @param id
     * @param customer
     * @return
     */
    @PutMapping("customers/{id}")
    public Customer updateCustomer(@PathVariable("id") int id, @RequestBody Customer customer) {
        customer.setId(id);
        customer.getQualifications().forEach(qualification -> {
            Customer c = new Customer();
            c.setId(id);
            qualification.setCustomer(c);
        });
        return customerManageService.updateCustomer(customer);
    }

    /**
     * 根据id修改抢房资格
     * @param id
     * @param qualifications
     * @return
     */
    @PutMapping("customers/{id}/update_qualifications")
    public Customer updateCustomerQualifications(@PathVariable("id") int id,
                                                 @RequestBody List<Qualification> qualifications){
        Customer customer = customerManageService.findCustomer(id);
        customerManageService.updateCustomerQualifications(customer,qualifications);
        customer = customerManageService.findCustomer(id);
        return customer;
    }

    /**
     * 根据id删除客户
     * @param id
     */
    @DeleteMapping("customers/{id}")
    public void removeCustomer(@PathVariable("id") int id){
        customerManageService.removeCustomer(id);
    }
}
